package com.ruoyi.common.utils;

import com.ruoyi.common.utils.file.FileUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;


public class FolderImageChecker {
    public static void main(String[] args) {


//        moveFiles("E:\\workdate\\菜谱生产\\picnum\\hecheng");

        numExtract( "E:\\workdate\\菜谱生产\\step7",7,7);
    }

    /**
     * 根据步骤数量提取图片
     * @param baseDirectory
     */
    private static void numExtract( String baseDirectory,Integer startNum,Integer endNum){

        File baseDir = new File(baseDirectory);

        if (baseDir.exists() && baseDir.isDirectory()) {
            processFolder(baseDir,startNum,endNum);
        } else {
            System.out.println("指定路径不存在或不是文件夹: " + baseDirectory);
        }
    }


    // 递归处理文件夹
    private static void processFolder(File folder,Integer startNum,Integer endNum) {
        boolean hasSubFolders = false;

        for (File subFile : folder.listFiles()) {
            if (subFile.isDirectory()) {
                hasSubFolders = true;
                processFolder(subFile,startNum,endNum); // 递归处理子文件夹
            }
        }

        // 如果没有子文件夹，这是一个最底层文件夹
        if (!hasSubFolders) {
            checkAndDeleteBottomFolder(folder,startNum,endNum);
        }
    }

    // 检查最底层文件夹的图片数量并删除不符合条件的文件夹
    private static void checkAndDeleteBottomFolder(File folder,Integer startNum,Integer endNum) {
        int imageCount = countImagesInFolder(folder);
        if (imageCount < startNum || imageCount > endNum) {
            deleteFolder(folder);
            System.out.println("已删除文件夹: " + folder.getAbsolutePath() + " (图片数量: " + imageCount + ")");
        } else {
            System.out.println("保留文件夹: " + folder.getAbsolutePath() + " (图片数量: " + imageCount + ")");
        }
    }

    // 统计文件夹中的图片数量
    private static int countImagesInFolder(File folder) {
        int count = 0;
        for (File file : folder.listFiles()) {
            if (file.isFile() && isImageFile(file)) {
                count++;
            }
        }
        return count;
    }

    // 判断文件是否为图片
    private static boolean isImageFile(File file) {
        String[] validExtensions = {".jpg", ".jpeg", ".png", ".bmp", ".gif", ".webp"}; // 支持的图片格式
        String fileName = file.getName().toLowerCase();
        for (String ext : validExtensions) {
            if (fileName.endsWith(ext)) {
                return true;
            }
        }
        return false;
    }

    // 删除文件夹及其内容
    private static void deleteFolder(File folder) {
        for (File file : folder.listFiles()) {
            if (file.isDirectory()) {
                deleteFolder(file);
            } else {
                file.delete();
            }
        }
        folder.delete();
    }

    /**
     * 移动图片到对应文件夹中
     * @param sourceFolderPath
     */
    public static void moveFiles(String sourceFolderPath) {
        Path sourceFolder = Paths.get(sourceFolderPath);  // 源文件夹路径
        // 目标文件夹路径

        try {
            Files.walk(sourceFolder)
                    .filter(Files::isRegularFile)
                    .forEach(path -> {
                        File file = path.toFile();
                        if (file.isFile() && isImageFile(file)){
                            String name = FileUtils.getNameNotSuffix(path.toString());
                            String[] laNames = name.split("_");
                            String laName = laNames[0];
                            String targetFolder = path.getParent() + "\\" + laName ;
//                        String targetFolder = path.getParent()+"\\"+ FileUtils.getNameNotSuffix(path.toString())+"_"+type;
                            System.out.println(targetFolder);
                            moveFile(path, Paths.get(targetFolder));
                        }


                    });

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static void moveFile(Path file, Path targetFolder) {
        // 检查目标文件夹是否存在
        if (!Files.exists(targetFolder) || !Files.isDirectory(targetFolder)) {
            System.out.println("目标文件夹不存在，跳过文件: " + file);
            return;
        }

        try {
            // 移动文件到目标文件夹
            Files.move(file, targetFolder.resolve(file.getFileName()), StandardCopyOption.REPLACE_EXISTING);
            System.out.println("文件已移动到目标文件夹: " + file.getFileName());
        } catch (IOException e) {
            System.out.println("移动文件时出错: " + file + " - " + e.getMessage());
        }
    }
}


